package com.example.file_management.utils;

import java.io.*;

public class FileConverter {

    private static final String LIBREOFFICE_PATH = "C:\\Program Files\\LibreOffice\\program\\soffice.exe";

    public static void convertToPDF(String inputFile, String outputFile) throws IOException, InterruptedException {
        File outputDir = new File(outputFile).getParentFile();
        if (!outputDir.exists()) {
            outputDir.mkdirs();
        }

        // 使用完整路径调用 LibreOffice
        String command = String.format("\"%s\" --headless --convert-to pdf --outdir \"%s\" \"%s\"",
                LIBREOFFICE_PATH, outputDir.getAbsolutePath(), inputFile);

        Process process = Runtime.getRuntime().exec(command);

        // 读取错误流，防止阻塞
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.err.println("LibreOffice: " + line);
            }
        }

        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new RuntimeException("文件转换失败，LibreOffice 退出码：" + exitCode);
        }
    }
}
